﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Sockets;
using System;
using Common;

public class ClientManager
{
	GameRoot gameRoot;
	public ClientManager(GameRoot gameRoot) {
		this.gameRoot = gameRoot;
	}

	const string ip = "127.0.0.1";
	const int port = 7788;
	Socket clientSocket;
	Message mes = new Message();


	public void OnInit() {
		clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

	}


	/// <summary>
	/// 连接服务器
	/// </summary>
	/// <param name="ip"></param>
	/// <param name="port"></param>
	public void ConnectServer(string ip, int port) {
		try {
			clientSocket.Connect(ip, port);
			StartRece();
			Debug.Log("连接成功!");
		} catch {
			Debug.Log("连接失败!");
		}
	}

	public void StartRece() {
		clientSocket.BeginReceive(mes.Data, mes.StartIndex, mes.RemainSize, SocketFlags.None, ReceiveCallBack, null);
	}
	public void ReceiveCallBack(IAsyncResult ar) {
		try {
			int count = clientSocket.EndReceive(ar);
			Debug.Log(count);
			mes.AddCount(count);
			mes.GetMessage(HandleResponse);
			StartRece();
		} catch (Exception e) {
			Debug.LogWarning(e);
			clientSocket.Close();
			return;
		}
	}



	/// <summary>
	/// 处理收到的服务器响应
	/// </summary>
	/// <param name="actionCode"></param>
	/// <param name="data"></param>
	public void HandleResponse(ActionCode actionCode, string data) {
		gameRoot.HandleResponse(actionCode, data);
		Debug.Log("Client,ActionCode:\t" + data);
	}

	/// <summary>
	/// 发送请求
	/// </summary>
	/// <param name="requestCode"></param>
	/// <param name="actionCode"></param>
	/// <param name="data"></param>
	public void SendRequest(RequestCode requestCode, ActionCode actionCode, string data) {
		byte[] requestData = mes.SendData(requestCode, actionCode, data);
		Debug.Log(data + "发送服务器");
		clientSocket.Send(requestData);
		
	}

}
